package com.cxs.musicplaywidget.view;

import com.cxs.musicplaywidget.data.EventParam;
import com.cxs.musicplaywidget.data.MDevice;
import com.cxs.musicplaywidget.player.data.MusicInfo;
import com.cxs.musicplaywidget.player.store.ImageStore;
import com.cxs.musicplaywidget.service.DeviceManager;
import com.cxs.musicplaywidget.service.ServiceManager;
import com.cxs.musicplaywidget.util.LogUtils;
import com.cxs.musicplaywidget.widget.controller.FormControllerManager;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.FormException;
import ohos.app.Context;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONException;
import ohos.utils.zson.ZSONObject;

import java.util.List;

import static com.cxs.musicplaywidget.constant.Const.WIDGET.*;

/**
 * @ClassName WidgetAdapter
 * @Author cxs
 * @Version 1.0
 * @Description 更新卡片视图
 * @Date 2022/03/10
 */
public class WidgetControllerAdapter implements IControllerAdapter {
    private static final String tag = WidgetControllerAdapter.class.getSimpleName();
    private Context context;
    private DeviceManager deviceManger;
    private ServiceManager serviceManager;

    public WidgetControllerAdapter(Context context) {
        this.context = context;
        deviceManger = DeviceManager.getInstance(context);
        serviceManager = ServiceManager.getInstance(context);
    }

    @Override
    public boolean isConnected(byte deviceIndex) {
        return serviceManager.isConnected(deviceIndex);
    }

    @Override
    public void updateDeviceList(boolean reload) {
        synchronized (DeviceManager.class) {
            List<MDevice> deviceList = deviceManger.getDeviceList();
            if (deviceList == null || deviceList.isEmpty()) {
                return;
            }
            byte deviceIndex = deviceManger.getCurrentIndex();
            LogUtils.debug(tag, "updateDeviceList.deviceList = " + deviceList);
            for (int i = 0; i < deviceList.size(); i++) {
                String cls = "";
                if (deviceList.get(i).proxy() != null) {
                    if (deviceIndex == i) {
                        cls = "connected_selected";
                    } else {
                        cls = "connected_unselected";
                    }
                } else {
                    cls = "disconnected";
                }
                deviceList.get(i).setCls(cls);
            }

            ZSONObject zsonObject = new ZSONObject();
            try {
                String zsonString = ZSONObject.toZSONString(deviceList);
                ZSONArray zsonArray = ZSONArray.stringToZSONArray(zsonString);
                zsonObject.put(DATA_DEVICE_LIST_KEY, zsonArray);
            } catch (ZSONException e) {
                LogUtils.debug(tag, "updateDeviceList Error converting JSON " + e.getMessage());
            }
            zsonObject.put(DATA_DEVICE_COUNT_KEY, deviceManger.getCount());
            zsonObject.put("deviceHeight2X4", deviceManger.getCount() * 24 + "px");

            updateWidget(new FormBindingData(zsonObject));
        }
    }

    @Override
    public void updatePlayerControl(EventParam.PlayerState playerState) {
        if (playerState == null) {
            return;
        }
        LogUtils.debug(tag, "updatePlayerControl.playerState= " + playerState.name());
        ZSONObject zsonObject = new ZSONObject();
        switch (playerState) {
            case NONE: {
                zsonObject.put(DATA_IS_PLAYING_KEY, false);
                zsonObject.put(DATA_CONNECTED_KEY, false);
                zsonObject.put(DATA_WAITING_KEY, true);
                break;
            }
            case PLAYING: {
                zsonObject.put(DATA_IS_PLAYING_KEY, true);
                zsonObject.put(DATA_CONNECTED_KEY, true);
                zsonObject.put(DATA_WAITING_KEY, false);
                zsonObject.put(DATA_WAVE_IMAGE_SRC_KEY, "wave_playing.gif");
                break;
            }
            case PREPARED:
                zsonObject.put(DATA_CONNECTED_KEY, true);
                zsonObject.put(DATA_WAITING_KEY, false);
                break;
            case PAUSED: {
                zsonObject.put(DATA_IS_PLAYING_KEY, false);
                zsonObject.put(DATA_CONNECTED_KEY, true);
                zsonObject.put(DATA_WAITING_KEY, false);
                zsonObject.put(DATA_WAVE_IMAGE_SRC_KEY, "wave_pause.png");
                break;
            }
        }
        updateWidget(new FormBindingData(zsonObject));
    }

    @Override
    public void updatePlaylist(EventParam eventParam) {
        List<MusicInfo> playList = eventParam.getPlayList();
        int playIndex = eventParam.getPlayIndex();
        int myPlayIndex = eventParam.getMyPlayIndex();
        if (playList == null || playList.isEmpty()) {
            deviceManger.getDevice().proxy().getPlayList();
            return;
        }
        ZSONArray zsonArray = new ZSONArray();
        for (int i = 0; i < playList.size(); i++) {
            MusicInfo musicInfo = playList.get(i);
            ZSONObject zsonObject = new ZSONObject();
            zsonObject.put(DATA_PLAY_LIST_INDEX_KEY, musicInfo.getIndex());
            zsonObject.put(DATA_PLAY_LIST_NAME_KEY, musicInfo.getName());
            zsonObject.put(DATA_PLAY_LIST_TITLE_KEY, musicInfo.getTitle());
            zsonObject.put(DATA_PLAY_LIST_ARTIST_KEY, musicInfo.getArtist());
            zsonObject.put(DATA_PLAY_LIST_CURRENT_KEY, playIndex == musicInfo.getIndex() ? true : false);
            zsonObject.put(DATA_PLAYING_CLS_KEY, playIndex == musicInfo.getIndex() ? "playing_cls" : "");
            LogUtils.debug(tag, "updatePlaylist.myPlayIndex=" + myPlayIndex + ", musicInfo.getIndex()=" + musicInfo.getIndex());

            if (eventParam.getDeviceIndex() != 0) {
                zsonObject.put(DATA_IS_REMOTE_KEY, true);
                if (myPlayIndex == musicInfo.getIndex() && eventParam.isPlaying()) {
                    zsonObject.put(DATA_MY_PLAY_IMAGE_KEY, "my_pause");
                } else {
                    zsonObject.put(DATA_MY_PLAY_IMAGE_KEY, "my_play");
                }
            } else {
                zsonObject.put(DATA_IS_REMOTE_KEY, false);
            }
            zsonArray.add(zsonObject);
        }
        System.out.println("zsonArray = " + zsonArray);
        ZSONObject zsonObject = new ZSONObject();
        zsonObject.put(DATA_PLAY_LIST_KEY, zsonArray);
        zsonObject.put(DATA_CONNECTED_KEY, true);
        zsonObject.put(DATA_WAITING_KEY, false);
        updateWidget(new FormBindingData(zsonObject));
    }

    @Override
    public void updateMusicInfo(MusicInfo musicInfo) {
        ZSONObject data = new ZSONObject();
        data.put("musicTitle", musicInfo.getTitle());
        updateWidget(new FormBindingData(data));
    }

    @Override
    public void updateVolume(int max, int vol) {
        ZSONObject zsonObject = new ZSONObject();
        int volume = Math.round(vol * 100 / max);
        LogUtils.debug(tag, "updateVolume.volume=" + volume);
        zsonObject.put("volume", volume);
        updateWidget(new FormBindingData(zsonObject));
    }

    @Override
    public void updateThumbnail(byte[] thumbnail, int index) {
        ZSONObject data = new ZSONObject();
        if (thumbnail == null || thumbnail.length <= 0) {
            data.put("imageSrc", "/common/cd2/" + index + ".png");
            updateWidget(new FormBindingData(data));
            return;
        }
        String name = "thumbnail" + System.currentTimeMillis() + ".png";
//        String name = musicInfo.getTitle() + ".png";

        // 通过内存图片方式添加图片
        data.put("imageSrc", "memory://" + name);
        data.put("musicTitle", "");

        FormBindingData bindingData = new FormBindingData(data);
        // 添加内存中的图片数据
        bindingData.addImageData(name, thumbnail);
        updateWidget(bindingData);
    }

    /**
     * 更新卡片
     * @param bindingData
     */
    private void updateWidget(FormBindingData bindingData) {
        LogUtils.debug(tag, "updateWidget.bindingData ="+bindingData.getDataString());
        List<Long> formIdList = getFormIdList();

        if (formIdList == null || formIdList.isEmpty()) {
            return;
        }
//        context.getUITaskDispatcher().syncDispatch( () -> {
            for (int i = 0; i < formIdList.size(); i++) {
                try {
                    boolean result = ((Ability) context).updateForm(formIdList.get(i), bindingData);
                    LogUtils.debug(tag, "updateWidget.formIdList.get(i)=" +formIdList.get(i)+ ",result=" + result);
                } catch (FormException e) {
                    LogUtils.error(tag, "updateWidget.err = " + formIdList.get(i));
                }
            }
//        });
    }

    public List<Long> getFormIdList() {
        FormControllerManager formControllerManager = FormControllerManager.getInstance(context);
        List<Long> allFormIdFromSharePreference = formControllerManager.getAllFormIdFromSharePreference();
        return allFormIdFromSharePreference;
    }


}
